/**
 * 
 */
package com.appwx.sdk.refreshlistview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.appwx.sdk.R;
import com.appwx.sdk.app.AppLoger;
import com.appwx.sdk.pla.lib.MultiColumnListView;

/**
 * 下拉刷新View
 * 支持嵌套listview,gridview,scrollview
 * @author xiajun
 *
 */
public class PullRefreshView extends LinearLayout {

	private static final String TAG = "PullToRefreshView";          
    // 下拉状态         
    private static final int PULL_UP_STATE = 0;          
    private static final int PULL_DOWN_STATE = 1;  
	
    // 刷新状态          
    private static final int PULL_TO_REFRESH = 2;          
    private static final int RELEASE_TO_REFRESH = 3;          
    private static final int REFRESHING = 4;   
    
    //下拉方式
    public static final int MODE_PULL_NONE = 0;          
    public static final int MODE_PULL_BOTH = 1;          
    public static final int MODE_PULL_UP = 2;          
    public static final int MODE_PULL_DOWN = 3;  
     
	//最后一次手势划动Y坐标        
    private int mLastMotionY;          
    
    private View mHeaderView,mFooterView;          
         
    //list or grid          
    private AdapterView<?> mAdapterView;  
	       
    //scrollview          
    private ScrollView mScrollView;          
     
    //多列listview          
    private MultiColumnListView mFallsView;  
    
    //HeadView和FooterView的高度
    private int mHeaderViewHeight, mFooterViewHeight;          
    
    private ImageView mHeaderImageView;          
    
    private TextView mHeaderTextView,mHeaderUpdateTextView,mFooterTextView;          
   
    private ProgressBar mHeaderProgressBar,mFooterProgressBar;          
  
    private LayoutInflater mInflater;          

    //HeadView和Footer 当前状态记录
    private int mHeaderState,mFooterState;          
   
    private int mPullState;  
              
    private RotateAnimation mFlipAnimation,mReverseFlipAnimation;          
    
    private OnFooterRefreshListener mOnFooterRefreshListener;          
   
    private OnHeaderRefreshListener mOnHeaderRefreshListener;          
  
    private String mLastUpdateTime;          
    private GestureDetector gestureDetector;  
    
    public interface OnFooterRefreshListener {public void onFooterRefresh(PullRefreshView view);}          
                     
    public interface OnHeaderRefreshListener {public void onHeaderRefresh(PullRefreshView view);} 
    
    //下拉手势检测
    private class PullDetector extends SimpleOnGestureListener {          
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {          
            if (Math.abs(distanceY) > Math.abs(distanceX)) {          
                return true;          
            }          
            return false;          
        }          
    } 
    
    private void measureView(View child) {          
        ViewGroup.LayoutParams p = child.getLayoutParams();          
        if (p == null) {          
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);          
        }          
                     
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);          
        int lpHeight = p.height;          
        int childHeightSpec;          
        if (lpHeight > 0) {          
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);          
        } else {          
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);          
        }          
        child.measure(childWidthSpec, childHeightSpec);          
    }  
    
    private void addHeaderView(){
        mHeaderView = mInflater.inflate(R.layout.xlistview_header, this, false);          
        mHeaderImageView = (ImageView) mHeaderView.findViewById(R.id.xlistview_header_arrow);          
        mHeaderTextView = (TextView) mHeaderView.findViewById(R.id.xlistview_header_hint_textview);   
        mHeaderUpdateTextView = (TextView) mHeaderView.findViewById(R.id.xlistview_header_time);
        mHeaderProgressBar = (ProgressBar) mHeaderView.findViewById(R.id.xlistview_header_progressbar);  
        
        //测量 mHeaderView        
        measureView(mHeaderView);          
        mHeaderViewHeight = mHeaderView.getMeasuredHeight(); //测量后HeadView的高度       
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mHeaderViewHeight);          
        // 设置topMargin的值为负的header View高度,即将其隐藏在最上方          
        params.topMargin = -(mHeaderViewHeight); //设置显示mHeaderView上边距等于HeadView的负高度        
        // mHeaderView.setLayoutParams(params1);          
        addView(mHeaderView, params);
    }
    
    private void addFooterView() {          
        mFooterView = mInflater.inflate(R.layout.xlistview_footer, this, false);          
        mFooterTextView = (TextView) mFooterView.findViewById(R.id.xlistview_footer_hint_textview);          
        mFooterProgressBar = (ProgressBar) mFooterView.findViewById(R.id.xlistview_footer_progressbar);          
       
        //测量 mFooterView         
        measureView(mFooterView);          
        mFooterViewHeight = mFooterView.getMeasuredHeight();          
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mFooterViewHeight);          
        // int top = getHeight();          
        // params.topMargin          
        // =getHeight();//在这里getHeight()==0,但在onInterceptTouchEvent()方法里getHeight()已经有值了,不再是0;          
        // getHeight()什么时候会赋值,稍候再研究一下          
        // 由于是线性布局可以直接添加,只要AdapterView的高度是MATCH_PARENT,那么footer view就会被添加到最后,并隐藏          
        addView(mFooterView, params);          
    }  
    
    //初始化
    private void init(){
    	gestureDetector = new GestureDetector(new PullDetector());
    	
    	//加载动画
    	mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    	mFlipAnimation.setInterpolator(new LinearInterpolator());          
        mFlipAnimation.setDuration(250);          
        mFlipAnimation.setFillAfter(true);     
        
        mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);          
        mReverseFlipAnimation.setInterpolator(new LinearInterpolator());          
        mReverseFlipAnimation.setDuration(250);          
        mReverseFlipAnimation.setFillAfter(true);          
                     
        mInflater = LayoutInflater.from(getContext());  
        
        addHeaderView();// header view 在此添加,保证是第一个添加到linearlayout的最上端 
    }
    
    //初始化adapterview像listview,gridview和scrollview
    private void initContentAdapterView(){
    	int count = getChildCount();          
        if (count < 3) {          
        	//这种布局必须包含3个子视图,并且adapterview或scrollview必须在第二个位置
            throw new IllegalArgumentException(          
                    "this layout must contain 3 child views,and AdapterView or ScrollView must in the second position!");          
        }          
        View view = null;          
        for (int i = 0; i < count - 1; ++i) {          
            view = getChildAt(i);          
            if (view instanceof MultiColumnListView) {          
                mFallsView = (MultiColumnListView) view;          
            }          
                                 
            if (view instanceof AdapterView<?>) {          
                mAdapterView = (AdapterView<?>) view;          
            }          
                                 
            if (view instanceof ScrollView) {          
                // finish later          
                mScrollView = (ScrollView) view;          
            }          
        }          
        if (mAdapterView == null && mScrollView == null && mFallsView == null) {       
        	//LineatLayou中必须包含AdapterView(list&grid)和ScorllView两种视图
            throw new IllegalArgumentException("must contain a AdapterView or ScrollView in this layout!");          
        } 
    }
           
    /**
     * 设置下拉模式       
     * @param mode
     */
    public void setMode(int mode) {          
        switch (mode) {          
        case MODE_PULL_NONE:          
            removeView(mHeaderView);          
            removeView(mFooterView);          
            break;          
        case MODE_PULL_DOWN:          
            removeView(mFooterView);          
            break;          
        case MODE_PULL_UP:          
            removeView(mHeaderView);          
            break;          
        default:          
            break;          
        }          
    }  
    
    /**          
     * header 准备刷新,手指移动过程,还没有释放          
     *           
     * @param deltaY          
     *            ,手指滑动的距离          
     */
    private void headerPrepareToRefresh(int deltaY) {          
        int newTopMargin = changingHeaderViewTopMargin(deltaY);          
        // 当header view的topMargin>=0时，说明已经完全显示出来了,修改header view 的提示状态          
        if (newTopMargin >= 0 && mHeaderState != RELEASE_TO_REFRESH) {          
            mHeaderTextView.setText(R.string.xlistview_header_hint_ready);          
            mHeaderImageView.clearAnimation();          
            mHeaderImageView.startAnimation(mFlipAnimation);          
            mHeaderState = RELEASE_TO_REFRESH;          
        } else if (newTopMargin < 0 && newTopMargin > -mHeaderViewHeight) {// 拖动时没有释放          
            mHeaderImageView.clearAnimation();          
            mHeaderImageView.startAnimation(mFlipAnimation);          
            // mHeaderImageView.          
            mHeaderTextView.setText(R.string.xlistview_header_hint_normal);          
            mHeaderState = PULL_TO_REFRESH;          
        }          
    }  
    
    /**          
     * 修改Header view top margin的值          
     *           
     * @description          
     * @param deltaY          
     * @return hylin 2012-7-31下午1:14:31          
     */
    private int changingHeaderViewTopMargin(int deltaY) {          
        LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();          
        float newTopMargin = params.topMargin + deltaY * 0.3f;          
        // 这里对上拉做一下限制,因为当前上拉后然后不释放手指直接下拉,会把下拉刷新给触发了,感谢网友yufengzungzhe的指出          
        // 表示如果是在上拉后一段距离,然后直接下拉          
        if (deltaY > 0 && mPullState == PULL_UP_STATE && Math.abs(params.topMargin) <= mHeaderViewHeight) {          
            return params.topMargin;          
        }          
        // 同样地,对下拉做一下限制,避免出现跟上拉操作时一样的bug          
        if (deltaY < 0 && mPullState == PULL_DOWN_STATE && Math.abs(params.topMargin) >= mHeaderViewHeight) {          
            return params.topMargin;          
        }          
        params.topMargin = (int) newTopMargin;          
        mHeaderView.setLayoutParams(params);          
        invalidate();          
        return params.topMargin;          
    }   
    
    /**          
     * footer 准备刷新,手指移动过程,还没有释放 移动footer view高度同样和移动header view          
     * 高度是一样，都是通过修改header view的topmargin的值来达到          
     *           
     * @param deltaY          
     *            ,手指滑动的距离          
     */
    private void footerPrepareToRefresh(int deltaY) {          
        int newTopMargin = changingHeaderViewTopMargin(deltaY);          
        // 如果header view topMargin 的绝对值大于或等于header + footer 的高度          
        // 说明footer view 完全显示出来了，修改footer view 的提示状态          
        if (Math.abs(newTopMargin) >= (mHeaderViewHeight + mFooterViewHeight) && mFooterState != RELEASE_TO_REFRESH) {          
            mFooterTextView.setText(R.string.xlistview_header_hint_ready);          
            mFooterState = RELEASE_TO_REFRESH;          
        } else if (Math.abs(newTopMargin) < (mHeaderViewHeight + mFooterViewHeight)) {          
            mFooterTextView.setText(R.string.xlistview_header_hint_normal);          
            mFooterState = PULL_TO_REFRESH;          
        }          
    }   
    
    /**          
     * 获取当前header view 的topMargin          
     *           
     * @description          
     * @return hylin 2012-7-31上午11:22:50          
     */
    private int getHeaderTopMargin() {          
        LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();          
        return params.topMargin;          
    } 
    
    /**          
     * 设置header view 的topMargin的值          
     *           
     * @description          
     * @param topMargin          
     *            ，为0时，说明header view 刚好完全显示出来； 为-mHeaderViewHeight时，说明完全隐藏了          
     *            hylin 2012-7-31上午11:24:06          
     */
    private void setHeaderTopMargin(int topMargin) {          
        LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();          
        params.topMargin = topMargin;          
        mHeaderView.setLayoutParams(params);          
        invalidate();          
    } 
    
    /**          
     * header refreshing          
     *           
     * @description hylin 2012-7-31上午9:10:12          
     */
    private void headerRefreshing() {          
        mHeaderState = REFRESHING;          
        setHeaderTopMargin(0);          
        mHeaderImageView.setVisibility(View.GONE);          
        mHeaderImageView.clearAnimation();          
        mHeaderImageView.setImageDrawable(null);          
        mHeaderProgressBar.setVisibility(View.VISIBLE);          
        mHeaderTextView.setText(R.string.xlistview_header_hint_loading);          
        if (mOnHeaderRefreshListener != null) {          
            mOnHeaderRefreshListener.onHeaderRefresh(this);          
        }          
    }          
                     
    /**          
     * footer refreshing          
     *           
     * @description hylin 2012-7-31上午9:09:59          
     */
    private void footerRefreshing() {          
        mFooterState = REFRESHING;          
        int top = mHeaderViewHeight + mFooterViewHeight;          
        setHeaderTopMargin(-top);          
        mFooterProgressBar.setVisibility(View.VISIBLE);          
        mFooterTextView.setText(R.string.xlistview_header_hint_loading);          
        if (mOnFooterRefreshListener != null) {          
            mOnFooterRefreshListener.onFooterRefresh(this);          
        }          
    } 
    
    /**          
     * header view 完成更新后恢复初始状态          
     *           
     * @description hylin 2012-7-31上午11:54:23          
     */
    public void onHeaderRefreshComplete() {          
        setHeaderTopMargin(-mHeaderViewHeight);          
        mHeaderImageView.setVisibility(View.VISIBLE);          
        mHeaderImageView.setImageResource(R.drawable.xlistview_arrow);          
        mHeaderTextView.setText(R.string.xlistview_header_hint_normal);          
        mHeaderProgressBar.setVisibility(View.GONE);          
        // mHeaderUpdateTextView.setText("");          
        mHeaderState = PULL_TO_REFRESH;          
    }
    
    /**          
     * Resets the list to a normal state after a refresh.          
     *           
     * @param lastUpdated          
     *            Last updated at.          
     */
    public void onHeaderRefreshComplete(CharSequence lastUpdated) {          
        setLastUpdated(lastUpdated);          
        onHeaderRefreshComplete();          
    } 
    
    /**          
     * Set a text to represent when the list was last updated.          
     *           
     * @param lastUpdated          
     *            Last updated at.          
     */
    public void setLastUpdated(CharSequence lastUpdated) {          
        if (lastUpdated != null) {          
            mHeaderUpdateTextView.setVisibility(View.VISIBLE);          
            mHeaderUpdateTextView.setText(lastUpdated);          
        } else {          
            mHeaderUpdateTextView.setVisibility(View.GONE);          
        }          
    }
    
    /**          
     * 是否应该到了父View,即PullToRefreshView滑动          
     *           
     * @param deltaY          
     *            , deltaY > 0 是向下运动,< 0是向上运动          
     * @return          
     */
    private boolean isRefreshViewScroll(int deltaY) {          
        if (mHeaderState == REFRESHING || mFooterState == REFRESHING) {          
            return false;          
        }          
        // 对于FallsView          
        if (mFallsView != null) {          
            if (deltaY > 0) {          
                View child = mFallsView.getChildAt(0);          
                if (child == null) {          
                    return false;          
                }          
                if (mFallsView.getFirstVisiblePosition() == 0 && child.getTop() == 0) {          
                    mPullState = PULL_DOWN_STATE;          
                    return true;          
                }          
                int top = child.getTop();          
                int padding = mFallsView.getPaddingTop();          
                if (mFallsView.getFirstVisiblePosition() == 0 && Math.abs(top - padding) <= 8) {          
                    mPullState = PULL_DOWN_STATE;          
                    return true;          
                }          
            } else if (deltaY < 0) {          
                                     
                View lastChild = mFallsView.getChildAt(mFallsView.getChildCount() - 1);          
                if (lastChild == null) {          
                    return false;          
                }          
                if (lastChild.getBottom() <= getHeight() && mFallsView.getLastVisiblePosition() == mFallsView.getCount() - 1) {          
                    mPullState = PULL_UP_STATE;          
                    return true;          
                }          
            }          
        }          
                     
        // 对于ListView和GridView          
        if (mAdapterView != null) {          
            // 子view(ListView or GridView)滑动到最顶端          
            if (deltaY > 0) {          
                     
                View child = mAdapterView.getChildAt(0);          
                if (child == null) {          
                    // 如果mAdapterView中没有数据,不拦截          
                    return false;          
                }          
                if (mAdapterView.getFirstVisiblePosition() == 0 && child.getTop() == 0) {          
                    mPullState = PULL_DOWN_STATE;          
                    return true;          
                }          
                int top = child.getTop();          
                int padding = mAdapterView.getPaddingTop();          
                if (mAdapterView.getFirstVisiblePosition() == 0 && Math.abs(top - padding) <= 8) {// 这里之前用3可以判断,但现在不行,还没找到原因          
                    mPullState = PULL_DOWN_STATE;          
                    return true;          
                }          
                     
            } else if (deltaY < 0) {          
                View lastChild = mAdapterView.getChildAt(mAdapterView.getChildCount() - 1);          
                if (lastChild == null) {          
                    // 如果mAdapterView中没有数据,不拦截          
                    return false;          
                }          
                // 最后一个子view的Bottom小于父View的高度说明mAdapterView的数据没有填满父view,          
                // 等于父View的高度说明mAdapterView已经滑动到最后          
                if (lastChild.getBottom() <= getHeight() && mAdapterView.getLastVisiblePosition() == mAdapterView.getCount() - 1) {          
                    mPullState = PULL_UP_STATE;          
                    return true;          
                }          
            }          
        }          
        // 对于ScrollView          
        if (mScrollView != null) {          
            // 子scroll view滑动到最顶端          
            View child = mScrollView.getChildAt(0);          
            if (deltaY > 0 && mScrollView.getScrollY() == 0) {          
                mPullState = PULL_DOWN_STATE;          
                return true;          
            } else if (deltaY < 0 && child.getMeasuredHeight() <= getHeight() + mScrollView.getScrollY()) {          
                mPullState = PULL_UP_STATE;          
                return true;          
            }          
        }          
        return false;          
    }  
    
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		int y = (int) ev.getRawY();          
        switch (ev.getAction()) {          
        case MotionEvent.ACTION_DOWN:          
            // 首先拦截down事件,记录y坐标          
            mLastMotionY = y;          
            break;          
        case MotionEvent.ACTION_MOVE:          
            // deltaY > 0 是向下运动,< 0是向上运动          
            int deltaY = y - mLastMotionY;          
            if (gestureDetector.onTouchEvent(ev)) {          
                if (isRefreshViewScroll(deltaY)) {          
                    return true;          
                }          
            } else {          
                return false;          
            }          
                     
            break;          
        case MotionEvent.ACTION_UP:          
        case MotionEvent.ACTION_CANCEL:          
            break;          
        }          
        return false;
	}
	
	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
        int y = (int) event.getRawY();          
        switch (event.getAction()) {          
        case MotionEvent.ACTION_DOWN:          
            // onInterceptTouchEvent已经记录          
            // mLastMotionY = y;          
            break;          
        case MotionEvent.ACTION_MOVE:          
            int deltaY = y - mLastMotionY;          
            if (mPullState == PULL_DOWN_STATE) {          
                AppLoger.info(TAG, " pull down!parent view move!");          
                headerPrepareToRefresh(deltaY);          
                // setHeaderPadding(-mHeaderViewHeight);          
            } else if (mPullState == PULL_UP_STATE) {          
                // PullToRefreshView执行上拉          
            	AppLoger.info(TAG, "pull up!parent view move!");          
                footerPrepareToRefresh(deltaY);          
            }          
            mLastMotionY = y;          
            break;          
        case MotionEvent.ACTION_UP:          
        case MotionEvent.ACTION_CANCEL:          
            int topMargin = getHeaderTopMargin();          
            if (mPullState == PULL_DOWN_STATE) {          
                if (topMargin >= 0) {          
                    // 开始刷新          
                    headerRefreshing();          
                } else {          
                    // 还没有执行刷新，重新隐藏          
                    setHeaderTopMargin(-mHeaderViewHeight);          
                }          
            } else if (mPullState == PULL_UP_STATE) {          
                if (Math.abs(topMargin) >= mHeaderViewHeight + mFooterViewHeight) {          
                    // 开始执行footer 刷新          
                    footerRefreshing();          
                } else {          
                    // 还没有执行刷新，重新隐藏          
                    setHeaderTopMargin(-mHeaderViewHeight);          
                }          
            }          
            break;          
        }
		return super.onTouchEvent(event);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
        addFooterView();    // footer view 在此添加保证添加到linearlayout中的最后         
        initContentAdapterView();   
	}

	@SuppressLint("NewApi")
	public PullRefreshView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public PullRefreshView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public PullRefreshView(Context context) {
		super(context);
		init();
	}

	
}
